package com.rsa.generate;

import com.rsa.common.RasCommon;
import com.rsa.entity.Keys;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyPair;
import java.security.KeyPairGenerator;

/**
 * @author lf
 * @Description: 生成密钥对
 * @date 2020/7/30 11:18
 */
public class GeneratorKey {

    private static final Logger log = LoggerFactory.getLogger(GeneratorKey.class);

    /**
     * 获取公私钥
     * @return  keys 秘钥对象
     * @throws Exception
     */
    public static Keys genKeyPair() throws Exception{
        log.info("生成公私钥....");
        KeyPair keyPair = getKeyPair();
        String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
        String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
        return new Keys(publicKey,privateKey);
    }

    /**
     * 生成密钥对
     * @return 密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(RasCommon.KEY_PAIRGENERATOR_SIZE[0]);
        return generator.generateKeyPair();
    }
}
